package com.qianyucc.blog.global;

import com.qianyucc.blog.exception.*;
import com.qianyucc.blog.model.entity.*;
import com.qianyucc.blog.mapper.*;
import lombok.extern.slf4j.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.stereotype.*;
import org.springframework.web.servlet.*;

import javax.servlet.http.*;

/**
 * @author lijing
 * @date 2019-10-19 10:53
 * @description 管理员token拦截器
 */
@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {
    @Autowired
    private ConfigMapper configMapper;

    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) {
        if ("OPTIONS".equals(req.getMethod())) {
            res.setStatus(HttpServletResponse.SC_OK);
            return true;
        }

        String token = req.getHeader("Authorization");
        log.info("admin token:" + token);
        if (token == null) {
            res.setStatus(403);
            res.setHeader("Access-Control-Allow-Origin", "*");
            return false;
        }
        ConfigDO cdo = configMapper.findByKey("admin_token");
        if (!cdo.getValue().equals(token)) {
            res.setStatus(403);
            res.setHeader("Access-Control-Allow-Origin", "*");
            return false;
        }
        return true;
    }
}